package com.gxa.community.admin.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.gxa.community.admin.realm.Auth2Token.Auth2Token;
import com.gxa.community.admin.service.system.LoginService;
import com.gxa.community.admin.util.JwtUtil;
import com.gxa.community.core.pojo.domain.Admin;
import com.gxa.community.core.utils.R;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShiroFilter extends AuthenticatingFilter {

    @Autowired
    LoginService loginService;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        String token = getToken((HttpServletRequest) servletRequest);
        System.out.println(token);
        if (StringUtils.isBlank(token)) return null;
        return new Auth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断是否为预检请求
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = getToken((HttpServletRequest) servletRequest);
        //从redis种查询token
        if (StringUtils.isBlank(token)) {
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json;charset=utf-8");
            servletResponse.getWriter().write(JSONUtils.toJSONString(R.error("请登陆后重试")));
            return false;
        }
        try {
            String username = JwtUtil.getSubject(token);
            if (loginService.queryAdminByName(username).getLoginStatus() == 0) {
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.setContentType("application/json;charset=utf-8");
                servletResponse.getWriter().write(JSONUtils.toJSONString(R.error("请重新登陆")));
            }
            servletRequest.setAttribute("token", token);
            SecurityUtils.getSubject().login(new Auth2Token(token));
        } catch (TokenExpiredException ignored) {
            // 设置响应的Header头新Token
            Admin admin = loginService.queryAdminByName(JwtUtil.getSubject(token));
            String token1 = JwtUtil.sign(JwtUtil.getSubject(token), JwtUtil.encodePsw(admin.getPassword(),
                            admin.getSalt()),
                    admin.getId(),
                    admin.getLoginAct());
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.setHeader("token", token1);
            httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
        } catch (Exception e) {
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json;charset=utf-8");
            servletResponse.getWriter().write(JSONUtils.toJSONString(R.error("登陆已过期, 请重新登陆")));
            return false;
        }
        return true;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        return super.onLoginFailure(token, e, request, response);
    }

    private String getToken(HttpServletRequest request) {
        String token;
        return StringUtils.isBlank(token = request.getHeader("token")) ? request.getParameter("token") : token;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        getSubject(request, response).login(new Auth2Token(getToken((HttpServletRequest) request)));
        return true;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); //标识允许哪个域到请求，直接修改成请求头的域
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");//标识允许的请求方法
        // 响应首部 Access-Control-Allow-Headers 用于 preflight request （预检请求）中，列出了将会在正式请求的 Access-Control-Expose-Headers 字段中出现的首部信息。修改为请求首部
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}

